package com.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.bean.Orders;
import com.wms.bean.Purchase;
import com.wms.config.Result;
import com.wms.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("purchase")
@CrossOrigin
public class PurchaseController {
    @Autowired
    PurchaseService purchaseService;

    @GetMapping("list")
    public Result getList() {
        List<Purchase> list = purchaseService.list();
        return Result.success(list);
    }

    @PostMapping("add")
    public Result add(@RequestBody Purchase purchase){
        purchaseService.save(purchase);
        Purchase purchaseSerivceById= purchaseService.getById(purchase.getPid());
        return Result.success("保存成功",purchaseSerivceById);
    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") int id){
        boolean b= purchaseService.removeById(id);
        if(b){
            return Result.success("删除成功");
        }else{
            return Result.fail(201,"删除失败");
        }
    }

    @PutMapping("update")
    public  Result edit(@RequestBody Purchase purchase){
        boolean b = purchaseService.updateById(purchase);
        Purchase purchase1=purchaseService.getById(purchase.getPid());
        if(b){
            return Result.success("修改成功", purchase1);
        }else{
            return Result.fail(201,"修改失败");
        }
    }
    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        IPage<Purchase> result;

        if (searchtext == null || searchtext.isEmpty()) {
            result =purchaseService.page(page);
        } else {
            QueryWrapper<Purchase> wrapper = new QueryWrapper<Purchase>();
            wrapper.like("pid", searchtext);

            result = purchaseService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }
}
